package com.richbond.sdjdsm.util.update;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.richbond.sdjdsm.R;
import com.richbond.sdjdsm.bean.UpdateBean;
import com.richbond.sdjdsm.util.UIHelp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2015/10/10.
 */
public class UpdateManager {
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    private static final String TAG = UpdateManager.class.getSimpleName();
    /* 是否取消更新 */
    private boolean cancelUpdate = false;
    /* 下载保存路径 */
    public static String mSavePath = Environment
            .getExternalStorageDirectory().getPath() + "/updateApk/";
    /* 记录进度条数量 */
    private int progress;
    private Context mContext;
    private ProgressBar mProgress;
    private TextView update_data;
    private Dialog mDownloadDialog;
    private static String apkFilePath = "";
    private UpdateBean updateBean;//更新的信息
    /*用于更新进度条、安装文件*/
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    update_data.setText(progress + "%");
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk(apkFilePath);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Context context, UpdateBean updateBean) {
        this.mContext = context;
        this.updateBean = updateBean;
    }

    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        if (isUpdate()) {
            // 显示提示对话框
            showNoticeDialog();
        } else {
            UIHelp.showToast(mContext, "当前已经是最新版本");
        }
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    public boolean isUpdate() {/**
     * 使用流读取 classpath 下文件:
     * 1.Android Studio Terminal
     * 2.cd appname\src\main\java
     * 3.jar cvf xml.jar persons.xml
     * 4.move xml.jar E:\AndroidStudio\Projects\Apps\appname\libs
     */
        // 获取当前软件版本
        int versionCode = getVersionCode(mContext);
        Log.v(TAG, "versionCode = " + versionCode);
        if (null != updateBean) {
            Log.v(TAG, "updateBean = " + updateBean.toString());
            int serviceCode = Integer.valueOf(updateBean.getAppVersionCode());
            // 版本判断
            if (serviceCode > versionCode) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    public int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {


        final AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_base1);
        TextView tvTip = (TextView) window.findViewById(R.id.tvTip);
        TextView tvTitle = (TextView) window.findViewById(R.id.tvTitle);
        Button btnLeft = (Button) window.findViewById(R.id.btnLeft);
        Button btnRight = (Button) window.findViewById(R.id.btnRight);

        tvTip.setText("软件更新");

        tvTitle.setText("检测到新版本，立即更新吗!");

        btnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showDownloadDialog();
                alertDialog.dismiss();
            }
        });

        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("正在更新");
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        update_data = (TextView) v.findViewById(R.id.update_data);
        update_data.setText("0%");
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        //设置点击外部时下载对话框不会消失
        mDownloadDialog.setCanceledOnTouchOutside(false);
        mDownloadDialog.show();
        // 下载文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    apkFilePath = mSavePath + updateBean.getAppVersionName() + ".apk";
                    Log.v(TAG, "mSavePath" + mSavePath);
                    URL url = new URL(updateBean.getAppDownloadUrl());
                    Log.v(TAG, "url=" + updateBean.getAppDownloadUrl());
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();


                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }

                    File apkFile = new File(apkFilePath);

//                    if (apkFile.exists()) {
//                        //Log.v(TAG,"MD5加密签名为："+MD5Util.getFileMD5String(apkFile));
//                        //判断apk的签名是否一致 一致就安装文件 不一致就会跳到外面去删除
//                            //安装文件
//                        installApk(apkFilePath);
//                        mDownloadDialog.dismiss();
//                        conn.disconnect();
//                        return;
//
//                    }

                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    conn.disconnect();
                    fos.close();
                    is.close();
                } else {
                    //吐司提示没有sd卡
                    new Thread() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            UIHelp.showToast(mContext, "请检查SD卡是否正确");
                            Looper.loop();
                        }
                    }.start();

                }
            } catch (MalformedURLException e) {
                Log.v(TAG, "urlException进入了这个异常");
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    }

    ;

    /**
     * 安装APK文件
     */
    private void installApk(String apkFilePath) {
        File apkfile = new File(apkFilePath);
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(intent);
        //apkfile.delete();
    }

    /**
     * 删除apk文件
     */
    public static void deleteApk() {
        //File apkfile = new File(apkFilePath);///storage/sdcard0/richbond/xssb/xssb_1.1.0.apk
        File apkfile = new File("/storage/sdcard0/richbond/xssb/xssb_1.1.0.apk");
        if (!apkfile.exists()) {
            return;
        }
        apkfile.delete();
    }
}
